import random
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response

from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView, CreateAPIView
from rest_framework_jwt.serializers import JSONWebTokenSerializer
from rest_framework_jwt.views import RefreshJSONWebToken

from ten_times import constants
from ten_times.libs.yuntongxun.ccp_sms import CCP
from users.models import User
from users.sers import CreateUserSer


class SmscodeView(APIView):

    def get(self, request, mobile):
        """
        获取短信验证码
        """
        redis_conn = get_redis_connection('default')

        # 生成短信验证码
        sms_code = "%06d" % random.randint(0, 999999)
        print(sms_code)

        # 创建redis管道对象
        pl = redis_conn.pipeline()

        # 保存短信验证码与发送记录
        pl.setex("sms_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex("send_flag_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)

        # 一次执行redis管道的所有命令
        pl.execute()

        # 发送短信验证码
        sms_code_expires = constants.SMS_CODE_REDIS_EXPIRES
        # try:
        #     ccp = CCP()
        #     # 调用云通信发送短信验证码
        #     res = ccp.send_template_sms(mobile, [sms_code, constants.expires], constants.SMS_CODE_TEMP_ID)
        # except Exception as e:
        #     return Response({"message": "发送短信异常"}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
        #
        # if res != 0:
        #     return Response({"message": "发送短信失败"}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        return Response({
            "message": "OK",
            "success": True,
            "sms_code": sms_code
        })


class CreateUser(GenericAPIView):
    serializer_class = CreateUserSer

    def post(self, request):

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 反序列化-数据保存(save内部会调用序列化器类的create方法)
        serializer.save()
        # a = JSONWebTokenSerializer()
        # print(a)

        return Response(serializer.data, status=status.HTTP_201_CREATED)



